import { useRef, useEffect, useMemo, useState } from 'react';
import config from '../config';

type MapKey = keyof typeof config.images;

export default function useImage() {
  const [isLoading, setIsLoading] = useState(true);
  const { current: imageMap } = useRef(new Map<MapKey, HTMLImageElement>());

  const promises = useMemo(() => {
    return Object.entries(config.images).map(([key, value]) => {
      return new Promise(resolve => {
        const img = new Image();
        img.src = value;
        img.onload = () => {
          imageMap.set(key as MapKey, img);
          resolve(img);
        };
      });
    });
  }, []);

  useEffect(() => {
    Promise.allSettled(promises).then(() => {
      setIsLoading(false);
    });
  }, []);

  return [isLoading, imageMap] as const;
}
